package engine

import (
	"container/list"
	"matching/enum"
	"matching/model"
)

type orderQueue struct {
	sortBy     enum.SortDirection
	parentList *list.List
	elementMap map[string]*list.Element  //每段价位的最新订单
}


func (q *orderQueue) Init(sortBy enum.SortDirection) {
	q.sortBy = sortBy
	q.parentList = list.New()
	q.elementMap = make(map[string]*list.Element)
}

func (q *orderQueue) findInsertPlaceElement(order *model.Order) *list.Element {

	//价格优先，时间优先
	for element := q.parentList.Front(); element != nil; element = element.Next() {
		tempValue := element.Value
		if tempValue.(*model.Order).Price.Cmp(order.Price)==0 {
			continue
		}
		if q.sortBy==enum.ASC {
			//升序，表示卖盘，价格低排前面
			if order.Price.Cmp(tempValue.(*model.Order).Price) >0 {
				return element
			}
		}else {
			//降序，表示买盘，价格高排前面
			if order.Price.Cmp(tempValue.(*model.Order).Price) <0 {
				return element
			}
		}
	}
	return nil
}

func (q *orderQueue) PutToQueue(order *model.Order) {
	if order.IsMarket() {
		//市价直接放到最后
		e:=q.parentList.PushBack(order)
		q.elementMap[order.Price.String()]=e
		return
	}
	if q.parentList.Len() == 0 {
		e:=q.parentList.PushFront(order)
		q.elementMap[order.Price.String()]=e
		return
	}
	//先找map中是否存在相同价格的
	if q.elementMap[order.Price.String()] !=nil {
		e:=q.parentList.InsertAfter(order,q.elementMap[order.Price.String()])
		q.elementMap[order.Price.String()]=e
		return
	}
	element := q.findInsertPlaceElement(order)
	if element != nil {
		e:=q.parentList.InsertBefore(order, element)
		q.elementMap[order.Price.String()]=e
		return
	}
}